//
//  CZUploadTaskVideoViewController.m
//  nsj_iOS
//
//  Created by apple on 2017/2/23.
//  Copyright © 2017年 GCZ. All rights reserved.
//

#import "CZUploadTaskVideoViewController.h"
#import "CZMyTaskImageCell.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "CZVideoPlayViewController.h"
static NSString *const task_video_cell = @"task_video_cell";

@interface CZUploadTaskVideoViewController () <UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *videoTableView;
@property (nonatomic, strong) UIImagePickerController *videoPicker;
@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, strong) NSMutableArray *localVideoArray;

@end

@implementation CZUploadTaskVideoViewController
- (NSMutableArray *__nonnull)imageArray {
    if (!_imageArray) {
        _imageArray = [[NSMutableArray alloc] init];
    }
    return _imageArray;
}

- (NSMutableArray *__nonnull)localVideoArray {
    if (!_localVideoArray) {
        _localVideoArray = [[NSMutableArray alloc] init];
    }
    return _localVideoArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"上传视频";
    _videoTableView.estimatedRowHeight = 75;
    _videoTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_videoTableView registerNib:[UINib nibWithNibName:@"CZMyTaskImageCell" bundle:nil] forCellReuseIdentifier:task_video_cell];
    // Do any additional setup after loading the view from its nib.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.videoArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CZMyTaskImageCell *cell = [tableView dequeueReusableCellWithIdentifier:task_video_cell];
    cell.playView.hidden = NO;
    cell.deleteBtn.hidden = NO;
    [cell.deleteBtn addTarget:self action:@selector(deleteVideo:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.iconView.yy_imageURL = [NSURL URLWithString:self.videoArray[indexPath.row][@"image"]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSURL *url = self.localVideoArray[indexPath.row];
    NSString *videoURL = self.videoArray[indexPath.row][@"video"];
//    NSString *URLStr = [url absoluteString];
    CZVideoPlayViewController *vc = [[CZVideoPlayViewController alloc] init];
    vc.videoURL = videoURL;
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)deleteVideo:(UIButton *)button {
    
    CZMyTaskImageCell *cell = (CZMyTaskImageCell *)button.superview.superview;
    NSIndexPath *indexPath = [self.videoTableView indexPathForCell:cell];
    
    [self.videoArray removeObjectAtIndex:indexPath.row];
    [self.videoTableView beginUpdates];
    [self.videoTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.videoTableView endUpdates];
    
    if (self.callBack) {
        self.callBack();
    }
    
}

- (IBAction)chooseVideo:(UIButton *)sender {
    [self chooseVideo];
}

#pragma mark - 选择视频
- (void)chooseVideo {
    UIAlertController *alertController = [[UIAlertController alloc] init];
    UIAlertAction *photoLibraryAction = [UIAlertAction actionWithTitle:@"视频库" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *videoPicker = [[UIImagePickerController alloc] init];
        videoPicker.delegate = self;
        videoPicker.allowsEditing = YES;
        videoPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        videoPicker.mediaTypes = [NSArray arrayWithObjects:(NSString *)kUTTypeMovie ,nil];
        [self presentViewController:videoPicker animated:YES completion:^{
        }];
    }];
    
    //访问受限
    NSString * mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍摄视频" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied) {
            UIAlertController * alertC = [UIAlertController alertControllerWithTitle:@"摄像头访问受限" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alertC animated:YES completion:nil];
            UIAlertAction * action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            [alertC addAction:action];
        } else if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeCamera)]) {
            UIImagePickerController *imageaPicker = [[UIImagePickerController alloc] init];
            UIImagePickerControllerSourceType sourceTypePhoto = UIImagePickerControllerSourceTypeCamera;
            imageaPicker.sourceType = sourceTypePhoto;
            imageaPicker.mediaTypes = @[(NSString *)kUTTypeMovie];

            imageaPicker.delegate = self;
            [self presentViewController:imageaPicker animated:YES completion:^{
                
            }];
        }
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertController addAction:photoLibraryAction];
    [alertController addAction:cameraAction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
    
}




#pragma mark - 选择Video
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSURL *videoUrl = [info objectForKey:UIImagePickerControllerReferenceURL];
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        videoUrl = [info objectForKey:UIImagePickerControllerMediaURL];
    }
    NSData *myVideoData = [NSData dataWithContentsOfURL:[info objectForKey:UIImagePickerControllerMediaURL]];
    
    
    [self uploadVideoWithData:myVideoData videoUrl:videoUrl];
    
    return;
    
}
- (UIImage *)getScreenShotImageFromVideoPath:(NSURL *)filePath{
    
    UIImage *shotImage;
    //视频路径URL
//    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:filePath options:nil];
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    gen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    shotImage = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    return shotImage;
}

#pragma mark - 上传视频到OSS
- (void)uploadVideoWithData:(NSData *)data videoUrl:(NSURL *)videoUrl{
    [SVProgressHUD show];
    
    [[[CZNsjHelper alloc] init] uploadVideoAsyncWithObjectKey:@"video" fileData:data completion:^(NSString *urlString) {
//        [SVProgressHUD showSuccessWithStatus:@"视频上传成功"];
        [SVProgressHUD showWithStatus:@"处理中.."];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            UIImage *image = [self getScreenShotImageFromVideoPath:videoUrl];
            NSData *compressData = UIImageJPEGRepresentation(image, 0.75);
            [[[CZNsjHelper alloc] init] uploadObjectSyncWithObjectKey:@"video_pic" fileData:compressData successStatus:@"" errorStatus:@"" completion:^(NSString *imageUrlStr) {
                [SVProgressHUD showSuccessWithStatus:@"上传成功"];
                NSDictionary *dic = @{@"video" : urlString, @"image" : imageUrlStr};
                [self.videoArray addObject:dic];
                [self.imageArray addObject:image];
                [self.localVideoArray addObject:videoUrl];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.videoTableView reloadData];
                    if (self.callBack) {
                        self.callBack();
                    }
                });
            } fail:^{
                [SVProgressHUD showErrorWithStatus:@"视频上传失败"];
            }];
        });
    } fail:^{
        [SVProgressHUD showSuccessWithStatus:@"视频上传失败"];
//        DLog(@"上传失败");
    }];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
